import socket
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import base64

# 创建 socket 对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 连接到服务器
server_address = ('172.20.10.6', 8888)
client_socket.connect(server_address)

# AES 加密配置（需与服务器端一致）
key = b'ThisIsASecretKey'  # 32字节密钥
iv = b'ThisIsAnIV4567890'  # 16字节初始化向量

def encrypt_data(plaintext):
    cipher = AES.new(key, AES.MODE_CBC, iv)
    ct_bytes = cipher.encrypt(pad(plaintext.encode(), AES.block_size))
    return base64.b64encode(ct_bytes).decode('utf-8')

while True:
    # 从文件读取要发送的内容
    with open('client_message.txt', 'r') as f:
        message = f.read()
    
    # 加密并发送数据
    encrypted_message = encrypt_data(message)
    client_socket.send(encrypted_message.encode('utf-8'))

    # 接收服务器响应
    encrypted_response = client_socket.recv(1024).decode('utf-8')
    
    # 解密并保存响应
    cipher = AES.new(key, AES.MODE_CBC, iv)
    pt = unpad(cipher.decrypt(base64.b64decode(encrypted_response)), AES.block_size)
    with open('client_received.txt', 'w') as f:
        f.write(pt.decode('utf-8'))
    print(f"已接收服务器响应，保存至 client_received.txt")
    break  # 单次通信后断开

# 关闭连接
client_socket.close()